package com.dhms.vostok1.ui.main.workbench

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.dhms.workbench.R
import com.dhms.workbench.databinding.FragmentWorkBenchBinding
import com.dhms.uikit.SpacesItemDecoration
import com.dhms.uikit.qrCodeScan.QRCodeScanActivity
import com.dhms.vostok1.adapter.WorkBenchListAdapter
import com.dhms.vostok1.data.device_center.DeviceListItemData
import com.dhms.vostok1.data.maintenance.TaskModuleType
import com.dhms.vostok1.data.work_bench.WorkBenchItem
import com.dhms.vostok1.data.work_bench.WorkBenchItemType
import com.dhms.vostok1.model.DeviceViewModel
import com.dhms.vostok1.model.UserViewModel
import com.dhms.vostok1.model.WebSocketViewModel
import com.dhms.vostok1.model.WorkBenchViewModel
import com.dhms.vostok1.ui.main.MainActivityInterface
import com.dhms.vostok1.utils.AppFeatureManager
import com.dhms.vostok1.utils.NetworkState
import com.dhms.vostok1.utils.Utils
import com.google.zxing.client.android.Intents
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanIntentResult
import com.journeyapps.barcodescanner.ScanOptions

class WorkBenchFragment : Fragment() {

    private var _binding: FragmentWorkBenchBinding? = null
    private val binding get() = _binding!!

    private val viewModel: WorkBenchViewModel by activityViewModels()
    private val userViewModel: UserViewModel by activityViewModels()
    private val deviceViewModel: DeviceViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentWorkBenchBinding.inflate(inflater, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.viewModel = viewModel
        binding.lifecycleOwner = viewLifecycleOwner

        setToolBar()

        setWorkBenchList()

        binding.alertBannerView.binding.buttonOption = {
          findNavController().navigate(R.id.action_workBenchFragment_to_spotPatrolSynchronizeTaskFragment)
        }
    }

    private fun setToolBar() {
        (activity as MainActivityInterface).setNotificationBadge(binding.topAppBar)
        binding.topAppBar.setOnMenuItemClickListener {
            if (WebSocketViewModel.instance.networkChange.value == NetworkState.NETWORK_NO) {
                errorTip(getString(R.string.offline_mode_unavailable))
                false
            } else {
                when (it.itemId) {
                    R.id.menu_notification -> {
                        findNavController().navigate(R.id.action_workBenchFragment_to_messageCenterFragment)
                        true
                    }
                    R.id.menu_scanning_qr_code -> {
                        val options =
                            ScanOptions().setCaptureActivity(QRCodeScanActivity::class.java)
                        barcodeLauncher.launch(options)

                        true
                    }
                    R.id.menu_nearby_equipment -> {
                        findNavController().navigate(R.id.action_workBenchFragment_to_nearbyDevicesFragment)
                        true
                    }
                    else -> false
                }
            }
        }
    }

    private val barcodeLauncher = registerForActivityResult(
        ScanContract()
    ) { result: ScanIntentResult ->
        if (result.contents == null) {
            val originalIntent = result.originalIntent
            if (originalIntent == null) {
                Log.d(TAG, "Cancelled scan")
            } else if (originalIntent.hasExtra(Intents.Scan.MISSING_CAMERA_PERMISSION)) {
                Log.d(
                    TAG,
                    "Cancelled scan due to missing camera permission"
                )
                Toast.makeText(
                    activity,
                    "请打开相机权限",
                    Toast.LENGTH_LONG
                ).show()
            }
        } else {
            Log.d(TAG, "Scanned")
            
            val deviceId = Utils.getQueryParameter(result.contents, Utils.deviceId)?.toLongOrNull()
            if (deviceId == null) {
                (activity as MainActivityInterface).showToast(
                    message = "获取不到设备id",
                )
                return@registerForActivityResult
            }

            (activity as MainActivityInterface).showToast(
                message = "正在获取设备信息",
                isLoading = true,
                timeOut = 15
            )

            deviceViewModel.getDeviceByDeviceId(deviceId) {
                (activity as MainActivityInterface).hideToast()
                if (it == null) {
                    (activity as MainActivityInterface).showToast(
                        message = "获取设备信息失败",
                    )
                } else {
                    deviceDetailJump(it)
                }
            }

        }
    }

    private fun deviceDetailJump(deviceData: DeviceListItemData) {
        deviceViewModel.setCurrentDevice(deviceData)
        deviceViewModel.clearDevicePartsData()
        val url = "${AppFeatureManager.deviceDetailUrl}?deviceId=${deviceData.deId}"
        val action = WorkBenchFragmentDirections.actionWorkBenchFragmentToWebViewFragment(url)
        findNavController().navigate(action)
    }


    private fun setWorkBenchList() {
        val workBenchAdapter = WorkBenchListAdapter {
            tapWorkBenchItem(it)
        }
        binding.workBenchListRecyclerView.layoutManager = LinearLayoutManager(context)
        binding.workBenchListRecyclerView.adapter = workBenchAdapter
        binding.workBenchListRecyclerView.addItemDecoration(
            SpacesItemDecoration(
                resources.getDimension(R.dimen.page_space),
                resources.getDimension(com.dhms.uikit.R.dimen.list_item_divider_space)
            )
        )
        viewModel.getWorkBenchList(userViewModel.userInfo.value?.privileges)
    }

    private fun tapWorkBenchItem(item: WorkBenchItem) {
        item.itemType?.let { itemType ->
            if (WebSocketViewModel.instance.networkChange.value == NetworkState.NETWORK_NO && itemType != WorkBenchItemType.SPOT_PATROL) {
                errorTip(getString(R.string.offline_mode_unavailable))
                return@let
            }

            var url: String? = null
            when (itemType) {
                WorkBenchItemType.DAMAGE -> url = AppFeatureManager.perilUrl
                WorkBenchItemType.FAULT -> url = AppFeatureManager.faultUrl
                WorkBenchItemType.SPOT_PATROL -> {
                    findNavController().navigate(R.id.action_workBenchFragment_to_spotPatrolFragment)
                    return@tapWorkBenchItem
                }
                WorkBenchItemType.LUBRICATION, WorkBenchItemType.MAINTENANCE -> {
                    val action =
                        WorkBenchFragmentDirections.actionWorkBenchFragmentToLubricationTaskFragment(
                            if (itemType == WorkBenchItemType.LUBRICATION) TaskModuleType.LUBRICATION else
                                TaskModuleType.MAINTENANCE
                        )
                    findNavController().navigate(action)
                    return@tapWorkBenchItem
                }
                WorkBenchItemType.REPAIR -> url = AppFeatureManager.repairUrl
                WorkBenchItemType.KNOWLEDGE -> url = AppFeatureManager.knowledgeUrl
                WorkBenchItemType.APPROVAL -> url = AppFeatureManager.approvalUrl
                WorkBenchItemType.PURCHASE -> url = AppFeatureManager.purchaseUrl
                WorkBenchItemType.WAREHOUSING -> url = AppFeatureManager.warehousingUrl
                WorkBenchItemType.WAREHOUSE_IN -> url = AppFeatureManager.warehouseInUrl
                WorkBenchItemType.EQUIPMENT_RETURN -> url = AppFeatureManager.equipmentReturnUrl
                WorkBenchItemType.WAREHOUSE_OUT -> url = AppFeatureManager.warehouseOutUrl
                WorkBenchItemType.EQUIPMENT_REQUISITION -> url = AppFeatureManager.equipmentRequisitionUrl
            }
            url?.let {
                val action =
                    WorkBenchFragmentDirections.actionWorkBenchFragmentToWebViewFragment(url)
                findNavController().navigate(action)
            }
        }
    }

    private fun errorTip(message: String?) {
        (activity as MainActivityInterface).showToast(
            R.drawable.ic_fail,
            message,
            false,
            2
        )
    }

    companion object {
        const val TAG = "WorkBenchFragment"
    }

}